/*
 * Aboboo Android
 * Copyright (C) 2012 www.aboboo.com
 * 
 */
package com.aboboo.android.activity;

import java.io.File;
import java.util.ArrayList;

import com.aboboo.android.R;

import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aboboo.android.database.AbobooDBService;
import com.aboboo.android.database.DwCourseware;

import com.aboboo.android.player.LyricPlayerService;
import com.aboboo.android.player.LyricPlayerServiceProxy;
import com.aboboo.android.player.MediaPlayerService;
import com.aboboo.android.player.SelectFileActivity;

/**
 * 正在学习页面
 * 
 * @author fangpeng
 * 
 * @version 1.0 2013-01-14
 * 
 */
public class StudyingNowActivity extends Activity implements
		LyricPlayerService.LyricPlayerListener,
		LyricPlayerServiceProxy.ServiceConnectionListener {

	private static final String TAG = "StudyingNowActivity";

	private LyricPlayerServiceProxy mProxy = new LyricPlayerServiceProxy(this);

	private EditText mLyricEdit = null;

	ArrayList<Integer> mLyricEndList = new ArrayList<Integer>();

	private class LyricMediaInfoProvider implements
			MediaPlayerService.MediaInfoProvider {
		String mUrl;
		String mTitle;

		LyricMediaInfoProvider(String url, String title) {
			mUrl = url;
			mTitle = title;
		}

		@Override
		public boolean moveToPrev() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean moveToNext() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public String getUrl() {
			return mUrl;
		}

		@Override
		public String getTitle() {
			// TODO Auto-generated method stub
			return mTitle;
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.studying_now);

		mLyricEdit = (EditText) this.findViewById(R.id.editLyric);

		mProxy.setConnectionListener(this);
		mProxy.setLyricPlayerListener(this);
		mProxy.setNotificationProvider(new MediaPlayerService.NotificationProvider() {
			@Override
			public Notification createNotification(Context context) {
				Notification notification = new Notification(
						R.drawable.button_blue_play, mProxy.getTitle(), System
								.currentTimeMillis());
				// The PendingIntent to launch our activity if the user selects
				// this notification
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, new Intent(context,
								StudyingNowActivity.class), 0);
				// Set the info for the views that show in the notification
				// panel.
				notification.setLatestEventInfo(context,
						getText(R.string.media_player_label),
						mProxy.getTitle(), contentIntent);
				return notification;
			}
		});
		mProxy.startAndBindService();
		mLyricEndList.clear();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		int btnId[] = { R.id.buttonPrev, R.id.buttonStop, R.id.buttonPlay,
				R.id.buttonPause, R.id.buttonNext };
		int btnSize = Math.min(metrics.widthPixels, metrics.heightPixels)
				/ (btnId.length + 1);

		// 调整按键尺寸。
		for (int i = 0; i < btnId.length; ++i) {
			ImageButton ib = (ImageButton) this.findViewById(btnId[i]);
			ib.setAdjustViewBounds(true);
			ib.setMaxHeight(btnSize);
			ib.setMaxWidth(btnSize);
		}
		ImageButton selectFile = (ImageButton) this
				.findViewById(R.id.buttonSelectFile);
		selectFile.setAdjustViewBounds(true);
		selectFile.setMaxHeight(btnSize * 2 / 3);
		selectFile.setMaxWidth(btnSize * 2 / 3);

		updateButtonState();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mProxy.setConnectionListener(null);
		mProxy.setLyricPlayerListener(null);
		if (!mProxy.isPlaying()) {
			mProxy.stopService();
		}
	}

	public void OnSelectFile(View v) {
		Intent i = new Intent(this, SelectFileActivity.class);
		startActivityForResult(i, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		Bundle bundle = data.getExtras();
		String title = bundle.getString(SelectFileActivity.KEY_FILE_TITLE_ID);
		if (title == null) {
			title = "NoTitile";
		}
		TextView tv = (TextView) this.findViewById(R.id.fileTitle);
		tv.setText(title);

		final String url = bundle.getString(SelectFileActivity.KEY_FILE_URL_ID);
		if (url != null) {
			mProxy.setMediaInfoProvider(new LyricMediaInfoProvider(url, title));
		}
	}

	public void OnOperationButtonClick(View v) {
		switch (v.getId()) {
		case R.id.buttonPrev:
			mProxy.seekToPrevLyric();
			break;
		case R.id.buttonStop:
			if (mProxy.isPlaying() || mProxy.isPausing()) {
				mProxy.stop();
			}
			break;
		case R.id.buttonPlay:
			if (!mProxy.isPlaying()) {
				mProxy.start();
			}
			break;
		case R.id.buttonPause:
			if (mProxy.isPlaying()) {
				mProxy.pause();
			}
			break;
		case R.id.buttonNext:
			mProxy.seekToNextLyric();
			break;
		}
	}

	protected void updateButtonState() {
		((ImageButton) this.findViewById(R.id.buttonPrev)).setEnabled(mProxy
				.isPlaying() || mProxy.isPausing());
		((ImageButton) this.findViewById(R.id.buttonStop)).setEnabled(mProxy
				.isPlaying() || mProxy.isPausing());
		((ImageButton) this.findViewById(R.id.buttonPlay)).setEnabled(mProxy
				.getDataSource() != null
				&& (!mProxy.isPlaying() || mProxy.isPausing()));
		((ImageButton) this.findViewById(R.id.buttonPause)).setEnabled(mProxy
				.isPlaying());
		((ImageButton) this.findViewById(R.id.buttonNext)).setEnabled(mProxy
				.isPlaying() || mProxy.isPausing());
	}

	// implement of LyricPlayerServiceProxy.ServiceConnectionListener
	public void onServiceConnected() {
		String title = mProxy.getTitle();
		if (title != null) {
			TextView tv = (TextView) this.findViewById(R.id.fileTitle);
			tv.setText(title);
		}
		updateButtonState();
	}

	public void onServiceDisconnected() {

	}

	// implement of LyricPlayerService.LyricPlayerListener
	public void onLyricLoaded() {
		mLyricEndList.clear();
		String lyric = new String();
		for (int i = 0; i < mProxy.getLyricCount(); ++i) {
			lyric += mProxy.getLyric(i);
			lyric += "\r\n";
			mLyricEndList.add(Integer.valueOf((lyric.length())));
		}
		mLyricEdit.setText(lyric);
	}

	public void onStateChanged() {
		updateButtonState();
	}

	public void onPositionChanged(long position) {

	}

	public void onLyricChanged(int lyric_index) {
		int lyricStart = 0;
		if (lyric_index > 0) {
			lyricStart = mLyricEndList.get(lyric_index - 1);
		}
		int lyricEnd = mLyricEndList.get(lyric_index);
		mLyricEdit.setSelection(lyricStart, lyricEnd);
		mLyricEdit.invalidate();
		Log.i(TAG, String.format("lyric= %d, setSelection(%d, %d)",
				lyric_index, lyricStart, lyricEnd));
	}

	public void OnLyricClick(View v) {
		EditText et = (EditText) v;
		int sel_start = et.getSelectionStart();
		for (int i = 0; i < mLyricEndList.size(); ++i) {
			if (sel_start < mLyricEndList.get(i)) {
				mProxy.seekToLyric(i);
				break;
			}
		}
	}
}

/**
 * 课件学习播放控制界面
 * 
 * @author fangpeng
 * @version 1.0 2013-01-14
 * 
 */
/**
 * public class StudyingNowActivity extends Activity {
 * 
 * private final static String ACTIVITY_TAG = "StudyingNowActivity";
 * 
 * private AbobooDBService dbService = null;
 * 
 * private TextView studying_textView;
 * 
 * @Override protected void onCreate(Bundle savedInstanceState) {
 *           super.onCreate(savedInstanceState);
 *           this.setContentView(R.layout.studying_now);
 * 
 *           Log.i(ACTIVITY_TAG, "switch to StudyingNowActivity"); findViews();
 *           initDbService(); setValues(); }
 * 
 *           private void findViews() { studying_textView = (TextView)
 *           findViewById(R.id.studying_course_text); }
 * 
 * 
 *           private void initDbService(){ dbService = new
 *           AbobooDBService(StudyingNowActivity.this); }
 * 
 *           public void setValues() { DwCourseware cw = (DwCourseware)
 *           getIntent().getParcelableExtra( CoursewaresListActivity.PAR_KEY);
 *           if (cw != null) { studying_textView.setText("正在学习:" +
 *           cw.toString()); } else { ArrayList<DwCourseware> cw_list =
 *           dbService.cwRecentStudy(); if(!cw_list.isEmpty()){
 *           studying_textView.setText("上次学习:" + cw_list.get(0).toString());
 *           }else{ studying_textView.setText("暂时没有学习列表，请添加课件学习列表"); } } }
 * @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode
 *           == KeyEvent.KEYCODE_BACK) { return getParent().onKeyDown(keyCode,
 *           event); } else { return super.onKeyDown(keyCode, event); } }
 * 
 *           }
 */
